<template>
  <div>
    <table class="table">
      <th>名称</th>
      <th>数量</th>
      <th>单价</th>
      <th>操作</th>
      <tbody>
        <tr v-for="{id, type, count, price} in list" :key="id">
          <td>{{type}}</td>
          <td><button @click="decrease(id)">-</button> {{count}} <button @click="increase(id)">+</button></td>
          <td>{{price}}</td>
          <td><button @click="deleteItem(id)">删除</button></td>
        </tr>
        <tr>
          <td><input type="text" v-model="newItem.type" placeholder="请填写类型"></td>
          <td><input type="number" v-model="newItem.count" placeholder="请填写数量"></td>
          <td><input type="number" v-model="newItem.price" placeholder="请填写价格"></td>
          <td><button @click="addItem">添加</button></td>
        </tr>
        <tr>
          <td colspan="4">总价：{{total}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'
// 查
const list = ref([
  { id: 1, type: '裤子', count: 3, price: 100 },
  { id: 2, type: '衣服', count: 1, price: 300 },
  { id: 3, type: '鞋子', count: 2, price: 200 },
])
// 增
let newItem = ref({ type: '', count: '', price: '' })
const addItem = () => {
  const { type, count, price } = newItem.value
  if (type && count && price && count >= 0 && price >= 0) {
    list.value.push({ id: new Date().getTime(), type, count, price })
    newItem.value.type = ''
    newItem.value.count = ''
    newItem.value.price = ''
  } else {
    alert('请填写各项，并且数量和价格必须大于0')
  }
}
// 删
const deleteItem = (id) => {
  list.value = list.value.filter(obj => obj.id !== id)
}
// 改
const increase = (id) => {
  const obj = list.value.find(obj => obj.id === id)
  obj.count += 1
}
const decrease = (id) => {
  const obj = list.value.find(obj => obj.id === id)
  obj.count -= 1
}
// 增删改都是改变list, list变化后computed出新的total
const total = computed(() => {
  return list.value.reduce((prev, cur) => {
    return prev + (cur.count * cur.price)
  }, 0)
})
</script>

<style scoped lang="less">
.table {
  border: 1px solid #ccc;
  th, tr, td {
    width: 150px;
    border: 1px solid #ccc;
    text-align: center;
  }
}
</style>
